package com.wbao.dianniu.im;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.conversation.IYWConversationService;
import com.alibaba.mobileim.conversation.YWConversation;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.Mode;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase.OnRefreshListener;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.data.NoticeJobData;
import com.wbao.dianniu.listener.INoticeJobListListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.NoticeJobListManager;
import com.wbao.dianniu.ui.BaseActivity;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.R;

/**
 * 面试通知
 * @author yejianjun
 *
 */
public class JobHelperActivity extends BaseActivity implements INoticeJobListListener{
	private PullToRefreshListView pullListView;
	private ListView mListView;
	private NoticeJobListManager manager;
	private MyAdapter adapter;
	private List<NoticeJobData> mList;
	private final int PAGE_COUNTS = 10;
	private int currentPage = 0;
	private Dialog dialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentLayout(R.layout.activity_recruit_helper);
		setTitleName("面试通知");
		init();
		requestData(currentPage);
		YWIMKit iMkit = LoginSampleHelper.getInstance().getIMKit();
		IYWConversationService conversationService = iMkit.getConversationService();
		YWConversation conversation = conversationService.getConversationByUserId("118", LoginSampleHelper.APP_KEY);
		if(null != conversation)
			conversationService.markReaded(conversation);
	}
	
	private void init() {
		pullListView = (PullToRefreshListView) findViewById(R.id.agent_listview);
		pullListView.setMode(Mode.PULL_UP_TO_REFRESH);
		pullListView.setOnRefreshListener(onRefreshListener);
		mListView = pullListView.getRefreshableView();
		registerForContextMenu(mListView);
		
		adapter = new MyAdapter(this);
		mList = new ArrayList<>();
		adapter.addData(mList);
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(itemClickListener);
		
	}
	OnRefreshListener onRefreshListener = new OnRefreshListener() {
		
		@Override
		public void onRefresh() {
			//  上拉刷新 加载请求数据
			pullUpRequest();
		}
	};
	
	OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			String address = mList.get(position-1).getAddress();
			showDialog(address);
		}
	};
	
	/**
	 * 显示收藏取消弹出框
	 */
	private void showDialog(final String address) {
		dialog = new Dialog(this, R.style.custom_Dialog);
		Window win = dialog.getWindow();
		win.getDecorView().setPadding(3, 3, 3, 3);
		win.setGravity(Gravity.BOTTOM);
		View view = LayoutInflater.from(this).inflate(R.layout.qa_collection_dialog, null);
		Button collectBtn = (Button) view.findViewById(R.id.qa_collection_button);
		Button cancelBtn = (Button) view.findViewById(R.id.qa_collection_cancel);
		collectBtn.setText("复制面试地点");
		// 收藏
		collectBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (null != dialog && dialog.isShowing()) {
					dialog.dismiss();
				}
				ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
				cmb.setText(address);
			}
		});
		// 取消
		cancelBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (null != dialog && dialog.isShowing()) {
					dialog.dismiss();
				}
			}
		});
		dialog.setContentView(view);
		dialog.setCancelable(true);
		dialog.show();
	}
	
	
	// 上拉刷新数据请求
	private void pullUpRequest(){
		//没有搜索结果 或者数据为空 上拉没有效果
		++currentPage ;
		requestData(currentPage);
	}
	private void requestData(int page) {
		manager = new NoticeJobListManager(this);
		manager.addNoticeJobListListener(this);
		manager.noticeJobList(GlobalContext.accountId, page * PAGE_COUNTS, PAGE_COUNTS);
	}
	
	class MyAdapter extends BaseAdapter{

		private Context mContext;
		private List<NoticeJobData> list;
		private LayoutInflater mInflater;
		public MyAdapter(Context context) {
			mContext = context;
			mInflater = LayoutInflater.from(mContext);
			if(null == list)
				list = new ArrayList<NoticeJobData>();
		}
		
		public void addData(List<NoticeJobData> addList){
			for (int i = 0; i < addList.size(); i++) {
				list.add(addList.get(i));
			}
		}
		public List<NoticeJobData> getList() {
			return list;
		}
		@Override
		public int getCount() {
			if (null == list)
				return 0;
			else
				return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			Holder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.job_msg_item, null);   
				holder = new Holder();
				holder.head = (ImageView)convertView.findViewById(R.id.user_head);
				holder.name =  (TextView)convertView.findViewById(R.id.user_name);
				holder.label =  (TextView)convertView.findViewById(R.id.user_label);
				holder.post =  (TextView)convertView.findViewById(R.id.job_msg_post);
				holder.time =  (TextView)convertView.findViewById(R.id.job_msg_time);
				holder.faceTime = (TextView) convertView.findViewById(R.id.job_msg_fcTime);
				holder.address =  (TextView)convertView.findViewById(R.id.job_msg_address);
				holder.sendMsg = (TextView) convertView.findViewById(R.id.msg_she);
				holder.contact =  (TextView)convertView.findViewById(R.id.contact_she);
				convertView.setTag(holder); 
			}else{
				 holder = (Holder) convertView.getTag();   
			}
			final NoticeJobData data = list.get(position);
			PictureDownloadUtils.displayHeadImage(mContext,holder.head, data.getHeadPic());
			holder.name.setText(data.getRealName()== null ? "" : data.getRealName());
			holder.label.setText(data.getLabel() == null ? "" : data.getLabel());
			holder.post.setText(data.getPost() == null ? "": data.getPost());
			holder.time.setText(data.getCreateDate() == null ? "" : data.getCreateDate());
			holder.faceTime.setText(data.getFacetime() == null ? "": data.getFacetime());
			holder.address.setText(data.getAddress() == null ? "": data.getAddress());
			holder.sendMsg.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					//跳转到聊天界面
					String appkey = getResources().getString(R.string.app_key);
					LoginSampleHelper.getInstance().openChat(mContext, GlobalContext.environment + String.valueOf(data.getAccountId()), appkey);
				}
			});
			holder.contact.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					String mobile = data.getMobile();
					callDialog(mobile);
				}
			});
			return convertView;
		}
		/**
		 * 拨打电话
		 */
		private void callDialog(final String mobile){
			CustomDialog.Builder builder = new CustomDialog.Builder(mContext); 
			builder.setTitle(mobile);
			builder.setMessageVisbily(true);
			builder.setTitleVisbily(true);
	        builder.setPositiveButton("呼叫", new DialogInterface.OnClickListener() {  
	            public void onClick(DialogInterface dialog, int which) {  
	                dialog.dismiss();  
	                Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+mobile));
					startActivity(intent);
	            }  
	        });  
	        builder.setNegativeButton("取消",  
	                new android.content.DialogInterface.OnClickListener() {  
	                    public void onClick(DialogInterface dialog, int which) {  
	                        dialog.dismiss();  
	                    }  
	                });  
	        builder.create().show();  
		}
		class Holder{
			public ImageView head;
			public TextView name;
			public TextView label;
			public ImageView sex;
			public TextView post;
			public TextView time;
			public TextView faceTime;
			public TextView address;
			public TextView sendMsg;
			public TextView contact;
		}
		
	}
	
	@Override
	public void onNoticeJobListFailure(int errorCode, String errorMsg) {
		pullListView.onRefreshComplete(false, false);
	}
	@Override
	public void onNoticeJobListSuccess(List<NoticeJobData> list) {
		pullListView.onRefreshComplete(false, false);
		if(null == list)
			return;
		adapter.addData(list);
		mList = adapter.getList();
		adapter.notifyDataSetChanged();
	}
	
}
